package com.lws.omapicompat.google

import android.content.Context
import android.os.Build
import android.se.omapi.Reader
import android.se.omapi.SEService
import androidx.annotation.RequiresApi
import com.lws.omapicompat.ReaderCompat
import com.lws.omapicompat.SEServiceCompat

import java.util.concurrent.Executor

@RequiresApi(Build.VERSION_CODES.P)
class SEServiceNew(context: Context, executor: Executor, listener: SEServiceCompat.OnConnectedListener) :
    SEServiceCompat {


    private val seService: SEService = SEService(context, executor) {
        listener.onConnected()
    }


    override fun getReaders(): Array<ReaderCompat> {
        return seService.readers.filterNotNull().map {
            ReaderNew(this, it)
        }.toTypedArray()
    }

    override fun getUiccReader(slotNumber: Int): ReaderCompat {
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.R){
            return ReaderNew(this,seService.getUiccReader(slotNumber))
        }
        val reader = seService.readers.find { reader: Reader ->
            return@find reader.name == "SIM$slotNumber" || reader.name == "UICC$slotNumber"
        }
            ?: throw IllegalArgumentException("the reader object corresponding to the uiccSlotNumber is not exist.")

        return ReaderNew(this, reader)
    }

    override fun getVersion(): String {
        return seService.version
    }

    override fun isConnected(): Boolean {
        return seService.isConnected
    }


    override fun shutdown() {
        seService.shutdown()
    }
}